package cn.wildfire.chat.kit.user;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;
import com.lqr.optionitemview.OptionItemView;
import com.sourcemuch.im.caiba.R;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.RequestCommonGroupEntity;
import cn.wildfire.chat.app.extendsion.classes.ResponseEntity;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.ui.VoipPopupWindow;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.WfcScheme;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.common.OperateResult;
import cn.wildfire.chat.kit.contact.ContactViewModel;
import cn.wildfire.chat.kit.contact.newfriend.InviteFriendActivity;
import cn.wildfire.chat.kit.conversation.ConversationActivity;
import cn.wildfire.chat.kit.qrcode.QRCodeActivity;
import cn.wildfire.chat.kit.third.utils.ImageUtils;
import cn.wildfire.chat.kit.utils.InputMethodUtils;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.model.UserInfoExtra;
import cn.wildfirechat.remote.ChatManager;

public class UserInfoFragment extends Fragment {
    @BindView(R2.id.portraitImageView)
    ImageView portraitImageView;
    @BindView(R2.id.nameTextView)
    TextView nameTextView;
    @BindView(R2.id.mobileTextView)
    TextView mobileTextView;
    @BindView(R2.id.nickyName)
    TextView nickyNameTextView;
    @BindView(R2.id.chatButton)
    LinearLayout chatButton;
    @BindView(R2.id.voipChatButton)
    LinearLayout voipChatButton;
    @BindView(R2.id.inviteButton)
    Button inviteButton;
    @BindView(R2.id.aliasOptionItemView)
    TextView aliasOptionItemView;

    @BindView(R2.id.qrCodeOptionItemView)
    OptionItemView qrCodeOptionItemView;
    @BindView(R2.id.genderImageView)
    ImageView genderImageView;
    @BindView(R2.id.phoneOptionItemView)
    OptionItemView phoneOptionItemView;
    @BindView(R2.id.reportOptionItemView)
    TextView reportOptionItemView;
    @BindView(R2.id.remarkTextView)
    TextView remarkTextView;
    @BindView(R2.id.remarkLayout)
    LinearLayout remarkLayout;
    @BindView(R2.id.groupRemarkTextView)
    TextView groupRemarkTextView;
    @BindView(R2.id.groupRemarkLayout)
    LinearLayout groupRemarkLayout;
    @BindView(R2.id.ll_delete_friend)
    LinearLayout llDeleteFriend;
    @BindView(R2.id.moreInfoOptionItemView)
    TextView moreInfoOptionItemView;
    @BindView(R2.id.ourcommongroupLayout)
    RelativeLayout ourcommongroupLayout;
    @BindView(R2.id.tv_our_common_group_count)
    TextView tv_our_common_group_count;

    private UserInfo userInfo;
    private GroupInfo groupInfo;
    private UserViewModel userViewModel;
    private ContactViewModel contactViewModel;
    private String myUid;
    private boolean fromGroupShow;
    private boolean commonGroupLayoutShow;

    public static UserInfoFragment newInstance(UserInfo userInfo, GroupInfo groupInfo,
                                               String MyUid, boolean fromGroupShow, boolean commonGroupLayoutShow) {
        UserInfoFragment fragment = new UserInfoFragment();
        Bundle args = new Bundle();
        args.putParcelable("userInfo", userInfo);
        args.putParcelable("groupInfo", groupInfo);
        args.putString("MyUID", MyUid);
        args.putBoolean("fromGroupShow", fromGroupShow);
        args.putBoolean("commonGroupLayoutShow", commonGroupLayoutShow);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * modify by HEKE , 2019/8/23 18:37
     * TODO 交友设置外部传入参数
     */
    int privateChat;
    boolean requestIsManager;
    boolean isFromGroupSet;

    /**
     * 绑定交友设置参数
     *
     * @param privateChat
     * @param requestIsManager
     */
    public void setPrivateChatAttrs(int privateChat, boolean requestIsManager) {
        this.privateChat = privateChat;
        this.requestIsManager = requestIsManager;
        this.isFromGroupSet = true;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        assert args != null;
        userInfo = args.getParcelable("userInfo");
        groupInfo = args.getParcelable("groupInfo");
        myUid = args.getString("MyUID");
        fromGroupShow = args.getBoolean("fromGroupShow", false);
        commonGroupLayoutShow = args.getBoolean("commonGroupLayoutShow", true);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_info_fragment, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        contactViewModel = WfcUIKit.getAppScopeViewModel(ContactViewModel.class);
        String selfUid = userViewModel.getUserId();
        if (selfUid.equals(userInfo.uid)) {
            // self
            chatButton.setVisibility(View.GONE);
            voipChatButton.setVisibility(View.GONE);
            inviteButton.setVisibility(View.GONE);
            qrCodeOptionItemView.setVisibility(View.VISIBLE);
            aliasOptionItemView.setVisibility(View.VISIBLE);
            phoneOptionItemView.setVisibility(View.VISIBLE);
            llDeleteFriend.setVisibility(View.GONE);
        } else if (contactViewModel.isFriend(userInfo.uid) || ChatManager.Instance().isMyBlackList(userInfo.uid)) {
            // friend
            chatButton.setVisibility(View.VISIBLE);
            voipChatButton.setVisibility(View.VISIBLE);
            inviteButton.setVisibility(View.GONE);
            moreInfoOptionItemView.setVisibility(View.VISIBLE);
            phoneOptionItemView.setVisibility(View.GONE);
            llDeleteFriend.setVisibility(View.VISIBLE);
        } else {
            // stranger
            chatButton.setVisibility(View.GONE);
            voipChatButton.setVisibility(View.GONE);
            inviteButton.setVisibility(View.VISIBLE);
            moreInfoOptionItemView.setVisibility(View.GONE);
            aliasOptionItemView.setVisibility(View.GONE);
            phoneOptionItemView.setVisibility(View.GONE);
            llDeleteFriend.setVisibility(View.GONE);
        }

        setUserInfo(userInfo);
        userViewModel.userInfoLiveData().observe(this, userInfos -> {
            for (UserInfo info : userInfos) {
                if (userInfo.uid.equals(info.uid)) {
                    userInfo = info;
                    setUserInfo(info);
                    break;
                }
            }
        });
        userViewModel.getUserInfo(userInfo.uid, true);

        /**
         * modify by HEKE , 2019/8/23 18:39
         * TODO 根据交友状态设置邀请好友按键显示或者隐藏
         */
        if (isFromGroupSet) {
            if (requestIsManager) {
                inviteButton.setVisibility(View.VISIBLE);
            } else {
                inviteButton.setVisibility((privateChat == 0) ? View.VISIBLE : View.GONE);
            }
            // 查看自身信息时，不允许显示添加通讯录
            if (userInfo.uid.equals(ChatManager.Instance().getUserId()) || contactViewModel.isFriend(userInfo.uid)) {
                inviteButton.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 设置用户信息显示
     *
     * @param userInfo
     */
    private void setUserInfo(UserInfo userInfo) {
        try {
            Glide.with(this).load(userInfo.portrait).apply(new RequestOptions().
                    placeholder(R.mipmap.avatar_def).centerCrop()).into(portraitImageView);
            // 自身看自己
            if (userInfo.uid.equals(userViewModel.getUserId())) {
                sameUserInfoSet();
                aliasOptionItemView.setText(getString(R.string.set_nickname));
                // 来自于群组显示自身信息
                if (fromGroupShow) {
                    aliasOptionItemView.setVisibility(View.GONE);
                    reportOptionItemView.setVisibility(View.GONE);
                    phoneOptionItemView.setVisibility(View.GONE);
                    qrCodeOptionItemView.setVisibility(View.GONE);
                    moreInfoOptionItemView.setVisibility(View.GONE);
                } else {
                    aliasOptionItemView.setVisibility(View.VISIBLE);
                    reportOptionItemView.setVisibility(View.GONE);
                    phoneOptionItemView.setVisibility(View.VISIBLE);
                    qrCodeOptionItemView.setVisibility(View.VISIBLE);
                }
            } else {
                // 好友
                if (ChatManager.Instance().isMyFriend(userInfo.uid) || ChatManager.Instance().isMyBlackList(userInfo.uid)) {
                    sameUserInfoSet();
                    phoneOptionItemView.setVisibility(View.GONE);
                } else {
                    sameUserInfoSet();
                    phoneOptionItemView.setVisibility(View.GONE);
                    reportOptionItemView.setVisibility(View.GONE);
                    showCommonGroupInfo();
                }
                aliasOptionItemView.setText(getString(R.string.set_remark));
            }
            genderImageView.setVisibility(View.GONE);
            phoneOptionItemView.setRightText("" + userInfo.mobile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置陌生人共同群显示
     */
    private void showCommonGroupInfo() {
        try {
            ourcommongroupLayout.setVisibility(commonGroupLayoutShow ? View.VISIBLE : View.GONE);
            ourcommongroupLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), OurCommonGroupActivity.class);
                    intent.putExtra("userInfo", userInfo);
                    startActivity(intent);
                }
            });
            HashMap<String, Object> params = new HashMap<>();
            params.put("frienduid", userInfo.uid);
            params.put("uid", ChatManager.Instance().getUserId());
            OkHttpRequest.getInstance(getActivity()).requestAsynJsonObject(ServerUrlClient.CHATTING_TOGETHER, params, new ReqCallBack<Object>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onReqSuccess(Object result) {
                    Gson gson = new Gson();
                    RequestCommonGroupEntity requestCommonGroupEntity = gson.fromJson(result.toString(), RequestCommonGroupEntity.class);
                    int groupCount = requestCommonGroupEntity.getResult().size();
                    tv_our_common_group_count.setText(groupCount + "" + getString(R.string.ge));
                }

                @Override
                public void onReqFailed(String errorMsg) {
                }
            }).request();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 共同的显示设置
     */
    @SuppressLint("SetTextI18n")
    private void sameUserInfoSet() {
        try {
            // 备注
            if (groupInfo != null) {
                userInfo = ChatManager.Instance().getUserInfo(userInfo.uid, groupInfo.target, true);
            }
            boolean friendRemarkNameNull = TextUtils.isTextEmpty(userInfo.friendAlias);
            remarkLayout.setVisibility(friendRemarkNameNull ? View.GONE : View.VISIBLE);
            if (!friendRemarkNameNull) {
                remarkTextView.setTypeface(Typeface.DEFAULT_BOLD);
                if (!TextUtils.isTextEmpty(userInfo.friendAlias)) {
                    remarkTextView.setText(userInfo.friendAlias);
                } else {
                    nameTextView.setText(getString(R.string.nick_name) + ":" + userInfo.displayName);
                }
                setTextViewStyle(remarkTextView, Typeface.DEFAULT_BOLD, 15, getContext().getResources().getColor(R.color.c252526));
                nameTextView.setText(getString(R.string.nick_name) + ":" + userInfo.displayName);
                setTextViewStyle(nameTextView, Typeface.DEFAULT, 12, getContext().getResources().getColor(R.color.c979899));
            } else {
                setTextViewStyle(nameTextView, Typeface.DEFAULT_BOLD, 15, getContext().getResources().getColor(R.color.c252526));
                nameTextView.setText(userInfo.displayName);
            }
            // 群昵称

            boolean groupRemarkNameNull = TextUtils.isTextEmpty(userInfo.groupAlias);
            groupRemarkLayout.setVisibility(groupRemarkNameNull ? View.GONE : View.VISIBLE);
            groupRemarkTextView.setText(getString(R.string.group_nick_name) + ":" + userInfo.groupAlias);
            setTextViewStyle(groupRemarkTextView, Typeface.DEFAULT, 12, getContext().getResources().getColor(R.color.c979899));
            // 其他
            if (!TextUtils.isTextEmpty(userInfo.extra)) {
                UserInfoExtra userInfoExtra = new Gson().fromJson(userInfo.extra, UserInfoExtra.class);
                if (userInfoExtra != null) {
                    nickyNameTextView.setText(getString(R.string.caiba_number) + ":" + userInfoExtra.getCaiba_number());
                } else {
                    nickyNameTextView.setText(getString(R.string.caiba_number) + ":");
                }
                setTextViewStyle(nickyNameTextView, Typeface.DEFAULT, 12, getContext().getResources().getColor(R.color.c979899));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置文本控件样式显示
     *
     * @param textView
     * @param typeface
     * @param textSize
     * @param textColor
     */
    private void setTextViewStyle(TextView textView, Typeface typeface, int textSize, int textColor) {
        try {
            textView.setTypeface(typeface);
            textView.setTextColor(textColor);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R2.id.chatButton)
    void chat() {
        Intent intent = new Intent(getActivity(), ConversationActivity.class);
        Conversation conversation = new Conversation(Conversation.ConversationType.Single, userInfo.uid, 0);
        intent.putExtra("conversation", conversation);
        startActivity(intent);
        getActivity().finish();
    }

    /**
     * 用户音视频选择窗口
     */
    protected VoipPopupWindow voipPopupWindow;

    @OnClick(R2.id.voipChatButton)
    void voipChat() {
        try {
            UserInfoActivity userInfoActivity = (UserInfoActivity) getActivity();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 权限申请
                String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
                userInfoActivity.requestPermissions(permissions, 100);
                for (String permission : permissions) {
                    boolean granted = userInfoActivity.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                    if (!granted) {
                        String msg = permission.equals(Manifest.permission.RECORD_AUDIO) ? "请允许打开语音权限!" : "请允许打开摄像头权限!";
                        Toast.makeText(userInfoActivity, msg, Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
            // TODO 音视频通话选择窗口
            if (voipPopupWindow == null) {
                voipPopupWindow = new VoipPopupWindow(userInfoActivity, new VoipPopupWindow.OnVoipSelecteListener() {
                    @Override
                    public void call(boolean isOnlyAudio) {
                        try {
                            WfcUIKit.onCall(getActivity(), userInfo.uid, true, isOnlyAudio);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            voipPopupWindow.showCenter();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDeletButtonVisiable(boolean visiable) {
        if (visiable == true) {
            llDeleteFriend.setVisibility(View.VISIBLE);
        } else {
            llDeleteFriend.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick(R2.id.aliasOptionItemView)
    void alias() {
        String selfUid = userViewModel.getUserId();
        if (selfUid.equals(userInfo.uid)) {
            Intent intent = new Intent(getActivity(), ChangeMyNameActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getActivity(), SetAliasActivity.class);
            intent.putExtra("userId", userInfo.uid);
            startActivity(intent);
        }
    }

    private static final int REQUEST_CODE_PICK_IMAGE = 100;

    @OnClick(R2.id.portraitImageView)
    void portrait() {
        if (userInfo.uid.equals(userViewModel.getUserId())) {
            /**
             * modify by HEKE , 2019/9/29 19:16 TODO 进入修改头像跳转界面
             */
            try {
                Intent intent = new Intent(getActivity(), ChangeHeadActivity.class);
                intent.putExtra("portrait", userInfo.portrait);
                getActivity().startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // TODO show big portrait
        }
    }

    private void updatePortrait() {
        ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            String imagePath = ImageUtils.genThumbImgFile(images.get(0).path).getAbsolutePath();
            MutableLiveData<OperateResult<Boolean>> result = userViewModel.updateUserPortrait(imagePath);
            result.observe(this, booleanOperateResult -> {
                if (booleanOperateResult.isSuccess()) {
                    Toast.makeText(getActivity(), getString(R.string.update_head_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), getString(R.string.update_head_success) + ": " + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick(R2.id.inviteButton)
    void invite() {
        Intent intent = new Intent(getActivity(), InviteFriendActivity.class);
        intent.putExtra("userInfo", userInfo);
        startActivity(intent);
        getActivity().finish();
    }

    @OnClick(R2.id.qrCodeOptionItemView)
    void showMyQRCode() {
        UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), false);
        String qrCodeValue = WfcScheme.QR_CODE_PREFIX_USER + userInfo.uid;
        startActivity(QRCodeActivity.buildQRCodeIntent(getActivity(), getString(R.string.qrcode_title), userInfo.portrait, qrCodeValue, userInfo));
    }

    @OnClick({R2.id.ll_delete_friend, R2.id.reportOptionItemView, R2.id.moreInfoOptionItemView})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_delete_friend) {
            TipDialog.showCustomDialog(getActivity(), getString(R.string.friendly_remainder), getString(R.string.delete_friend_msg)
                    , new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE
                    , true, 2, true, new TipDialog.OnMsgTipDialogListener() {
                        @Override
                        public void then(boolean confirm, boolean outtouch) {
                            if (confirm) {
                                String userId = userInfo.uid;
                                ContactViewModel contactViewModel = WfcUIKit.getAppScopeViewModel(ContactViewModel.class);
                                contactViewModel.deleteFriend(userId).observe(getActivity(), booleanOperateResult -> {
                                            if (booleanOperateResult.isSuccess()) {
                                                getActivity().finish();
                                            } else {
                                                Toast.makeText(getContext(), getString(R.string.delete_friend_error) + ""
                                                        + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                );
                            }
                        }
                    });
        } else if (id == R.id.reportOptionItemView) {
            ShowReportPopWindow();
        } else if (id == R.id.moreInfoOptionItemView) {
            Intent intent = new Intent(getActivity(), SocialDataActivity.class);
            intent.putExtra("userInfo", userInfo);
            startActivity(intent);
        }
    }


    PopupWindow popupWindow;

    private void ShowReportPopWindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_report, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);

        Button cancel = view.findViewById(R.id.btn_cancel);
        Button confirm = view.findViewById(R.id.btn_confirm);
        EditText etReport = view.findViewById(R.id.et_report);
        etReport.setFocusable(true);
        etReport.setFocusableInTouchMode(true);
        etReport.requestFocus();
        InputMethodUtils.showOrHide(getActivity());
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String reportText = etReport.getText().toString().trim();
                if (TextUtils.isTextEmpty(reportText)) {
                    ToastTip.tip(getString(R.string.message_can_not_null));
                    return;
                }
                HashMap<String, Object> params = new HashMap<>();
                myUid = userViewModel.getUserId();
                params.put("from", myUid);
                params.put("message", reportText);
                params.put("target", userInfo.uid);
                params.put("type", "1");
                OkHttpRequest.getNewInstance(getActivity()).requestAsynJsonObject(ServerUrlClient.REQUEST_REPORT_FRIEND, params, new ReqCallBack<Object>() {
                    @Override
                    public void onReqSuccess(Object result) {
                        try {
                            String ret = result.toString();
                            if (ret != null) {
                                ResponseEntity<JsonObject, String> responseEntity = new ResponseEntity(result.toString());
                                if (responseEntity.isSuccess()) {
                                    Toast.makeText(getActivity(), "举报成功,我们将在24小时内处理.", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getActivity(), "举报失败", Toast.LENGTH_SHORT).show();
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {

                    }
                }).request();
                popupWindow.dismiss();
            }
        });


        setAlph(0.9f);
        popupWindow.showAtLocation(reportOptionItemView, Gravity.CENTER, 0, 0);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlph(1f);
            }
        });

    }

    private void setAlph(float f) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        //0.0-1.0
        lp.alpha = f;
        getActivity().getWindow().setAttributes(lp);
    }
}
